﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using Framework;

namespace Enterprise
{
    public class BusinessCardCategoryService : BaseService
    {
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public Table GetTable()
        {
            var table = new Table
            {
                Rows = DbHelperSql.Query("select * from TbBusinessCardCategory order by cosort desc").Tables["ds"].Rows,
                Total = DbHelperSql.GetSingle("select count(*) from TbBusinessCardCategory").SafeToInt()
            };
            return table;
        }
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            return DbHelperSql.Query("select A.CoName,A.CoNormalImage,A.CoSmallImage,A.CoBigImage,A.CoNameEn,A.CoBusinessCardCategoryId,A.CoSort,B.CoName as CoParentName  from TbBusinessCardCategory as A left join TbBusinessCardCategory as B on A.CoParentId=B.CoBusinessCardCategoryId where A.CoBusinessCardCategoryId={0}".FormatWith(id)).Tables["ds"].Rows[0];
        }

        /// <summary>
        /// 添加分类
        /// </summary>
        /// <param name="name">分类名称</param>
        /// <param name="nameEn"> </param>
        /// <param name="parentId">父级ID</param>
        /// <param name="sort">排序</param>
        /// <param name="filedata"> </param>
        public int Add(string name, string nameEn, int parentId, int sort, HttpPostedFileBase filedata = null)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "分类名称");
            Check.Argument.IsNotOutOfLength(nameEn, 2, 50, "分类名称(En)");
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                                       {
                                           PostedFile = filedata,
                                           RelativePath = BusinessCardCategoryConfig.RelativePath,
                                           IsAdaptive = BusinessCardCategoryConfig.IsAdaptive,
                                           IsImage = true,
                                           IsGenerateThumbnail = BusinessCardCategoryConfig.IsGenerateThumbnail,
                                           FileMaxLength = BusinessCardCategoryConfig.ImageSize,
                                           ThumbnailHeight = BusinessCardCategoryConfig.ThumbnailHeight,
                                           ThumbnailWidth = BusinessCardCategoryConfig.ThumbnailWidth,
                                           ThumbnailPrefix = BusinessCardCategoryConfig.ThumbnailPrefix
                                       };
                uploadHelper.Save();
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var sbSql = new StringBuilder();
            sbSql.Append("insert into TbBusinessCardCategory(");
            sbSql.Append("CoName,CoNameEn,CoType,CoLanguage,CoSort,CoNormalImage,CoSmallImage,CoBigImage,CoCategoryPath,CoParentId,CoDepth");
            sbSql.Append(")");
            sbSql.Append(" values (");
            sbSql.Append("@CoName,@CoNameEn,@CoType,@CoLanguage,CoSort,@CoNormalImage,@CoSmallImage,@CoBigImage,@CoCategoryPath,@CoParentId,@CoDepth");
            sbSql.Append(")");
            SqlParameter[] parameters =
                {
                    new SqlParameter("@CoName", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoNameEn", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoType", SqlDbType.Int),
                    new SqlParameter("@CoLanguage", SqlDbType.VarChar, 10),
                    new SqlParameter("@CoSort", SqlDbType.Int),
                    new SqlParameter("@CoNormalImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoSmallImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoBigImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoCategoryPath", SqlDbType.Text),
                    new SqlParameter("@CoParentId", SqlDbType.Int),
                    new SqlParameter("@CoDepth", SqlDbType.Int)
               
                };
            parameters[0].Value = name;
            parameters[1].Value = nameEn;
            parameters[2].Value = 0;
            parameters[3].Value = DBNull.Value;
            parameters[4].Value = sort;
            parameters[5].Value = fileName;
            parameters[6].Value = thumFileName;
            parameters[7].Value = fileName;
            using (var sdr = DbHelperSql.ExecuteReader("select * from TbBusinessCardCategory where CoBusinessCardCategoryId={0}".FormatWith(parentId)))
            {
                if (sdr.Read())
                {
                    parameters[8].Value = sdr["CoCategoryPath"].SafeToString() + parentId + ",";
                    parameters[9].Value = parentId;
                    parameters[10].Value = sdr["CoDepth"].SafeToInt() + 1;
                    if ((sdr["CoDepth"].SafeToInt() + 1) > BusinessCardCategoryConfig.BusinessCardCategoryDepth)
                    {
                        throw new Exception("律师名片分类深度不能超过{0}".FormatWith(BusinessCardCategoryConfig.BusinessCardCategoryDepth));
                    }
                }
                else
                {
                    parameters[8].Value = "";
                    parameters[9].Value = DBNull.Value;
                    parameters[10].Value = 1;
                }
            }
            var obj = DbHelperSql.Add(sbSql.ToString(), parameters).SafeToInt32();
            return obj;

        }


        public void Edit(int id, string name, string nameEn, int sort, HttpPostedFileBase filedata = null)
        {
            Check.Argument.IsNotOutOfLength(name, 2, 50, "分类名称");
            Check.Argument.IsNotOutOfLength(nameEn, 2, 50, "分类名称(En)");
            var fileName = string.Empty;
            var thumFileName = string.Empty;
            if (filedata != null && filedata.ContentLength > 0)
            {
                var uploadHelper = new UploadHelper
                {
                    PostedFile = filedata,
                    RelativePath = BusinessCardCategoryConfig.RelativePath,
                    IsAdaptive = BusinessCardCategoryConfig.IsAdaptive,
                    IsImage = true,
                    IsGenerateThumbnail = BusinessCardCategoryConfig.IsGenerateThumbnail,
                    FileMaxLength = BusinessCardCategoryConfig.ImageSize,
                    ThumbnailHeight = BusinessCardCategoryConfig.ThumbnailHeight,
                    ThumbnailWidth = BusinessCardCategoryConfig.ThumbnailWidth,
                    ThumbnailPrefix = BusinessCardCategoryConfig.ThumbnailPrefix
                };
                uploadHelper.Save();
                fileName = uploadHelper.FileName;
                thumFileName = uploadHelper.ThumbnailFileName;
            }
            var sbSql = new StringBuilder();
            sbSql.Append("update TbBusinessCardCategory set ");
            sbSql.Append(" CoName=@CoName,");
            sbSql.Append(" CoNameEn=@CoNameEn,");
            sbSql.Append(" CoNormalImage=@CoNormalImage,");
            sbSql.Append(" CoSmallImage=@CoSmallImage,");
            sbSql.Append(" CoBigImage=@CoBigImage,");
            sbSql.Append(" CoSort=@CoSort ");
            sbSql.Append(" where CoBusinessCardCategoryId=@id ");
            SqlParameter[] parameters =
                {
                    new SqlParameter("@CoName", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoNameEn", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoNormalImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoSmallImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoBigImage", SqlDbType.VarChar, 255),
                    new SqlParameter("@CoSort", SqlDbType.Int),
                    new SqlParameter("@id", SqlDbType.Int)
                };
            parameters[0].Value = name;
            parameters[1].Value = nameEn;
            if (filedata != null && filedata.ContentLength > 0)
            {
                parameters[2].Value = fileName;
                parameters[3].Value = thumFileName;
                parameters[4].Value = fileName;
            }
            parameters[5].Value = sort;
            parameters[6].Value = id;
            var path = HttpContext.Current.Server.MapPath(BusinessCardCategoryConfig.RelativePath);
            var ds = DbHelperSql.Query("select * from TbBusinessCardCategory where CoBusinessCardCategoryId={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            var obj = DbHelperSql.ExecuteSql(sbSql.ToString(), parameters).SafeToInt();
            if (!(obj > 0))
            {
                throw new Exception("记录不存在！");
            }
        }

        public void Delete(int id)
        {
            var syscount = DbHelperSql.GetSingle("select count(*) from TbBusinessCardCategory  where CoBusinessCardCategoryId={0}  and coissystem=1".FormatWith(id)).SafeToInt();
            if (syscount > 0)
            {
                throw new Exception("系统项不能删除！");
            }
            var childcount = DbHelperSql.GetSingle("select count(*) from TbBusinessCardCategory  where coparentid={0} ".FormatWith(id)).SafeToInt();
            if (childcount > 0)
            {
                throw new Exception("该分类存在子类，请先删除子类！");
            }
            var count = DbHelperSql.GetSingle("select count(*) from TbBusinessCard  where CoBusinessCardCategoryId={0}".FormatWith(id)).SafeToInt();
            if (count > 0)
            {
                throw new Exception("该分类下存在名片，请先删除名片记录！");
            }
            var path = HttpContext.Current.Server.MapPath(BusinessCardCategoryConfig.RelativePath);
            var ds = DbHelperSql.Query("select * from TbBusinessCardCategory where CoBusinessCardCategoryId={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoNormalImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoSmallImage"].SafeToString()));
                FileHelper.DeleteSub(Path.Combine(path, item["CoBigImage"].SafeToString()));
            }
            var obj = DbHelperSql.ExecuteSql("delete from TbBusinessCardCategory where CoBusinessCardCategoryId={0} ".FormatWith(id)).SafeToInt();
            if (!(obj > 0))
            {
                throw new Exception("记录不存在！");
            }
        }

    }
}
